import 'package:flutter/material.dart' show ValueSetter;
import 'package:permission_handler/permission_handler.dart';
import 'package:xf_evaluate/utils/platform_utils.dart';

import 'toast_utils.dart';

/// 权限工具类
class PermissionUtils {
  /// 检测需使用的权限
  static Future<bool> _checkPermission(
    List<Permission> permissions, {
    ValueSetter<Permission>? permanentlyDeniedCallback,
  }) async {
    final List<PermissionStatus> statusList = await Future.wait(
      permissions.map((Permission element) => element.status),
    );
    final List<Permission> needGrantedPermission = <Permission>[];
    statusList.asMap().forEach((int key, PermissionStatus value) {
      if (value != PermissionStatus.granted) {
        needGrantedPermission.add(permissions[key]);
      }
    });
    if (needGrantedPermission.isNotEmpty) {
      final Map<Permission, PermissionStatus> statusMap =
          await needGrantedPermission.request();
      for (int i = 0; i < statusMap.values.length; i++) {
        if (statusMap.values.elementAt(i) ==
            PermissionStatus.permanentlyDenied) {
          permanentlyDeniedCallback?.call(statusMap.keys.elementAt(i));
          return false;
        } else if (statusMap.values.elementAt(i) != PermissionStatus.granted) {
          return false;
        }
      }
    }
    return true;
  }

  /// 检测存储权限
  static Future<bool> checkStoragePermission({
    ValueSetter<Permission>? permanentlyDeniedCallback,
  }) {
    if (!PlatformUtils.isAndroid) {
      return Future<bool>.value(true);
    }
    return _checkPermission(
      <Permission>[Permission.storage],
      permanentlyDeniedCallback: permanentlyDeniedCallback ??
          (Permission permission) {
            ToastUtils.showShort('请前往设置开启存储权限');
          },
    );
  }
}
